package com.pine.dcts.utils;


import com.pine.app.module.security.core.Authentication;
import com.pine.app.module.security.core.SecurityContextHolder;
import com.pine.app.module.security.core.common.enums.ErrorType;
import com.pine.app.module.security.core.userdetails.UserDetails;
import com.pine.app.module.security.oauth.exception.AuthenticationException;
import com.pine.app.module.security.oauth.user.password.BCryptPasswordEncoder;
import com.pine.app.module.security.oauth.user.password.PasswordEncoder;
import com.pine.dcts.entity.User;

/**
 * @Description: security工具类
 * @Author: xyjxust
 * @Date: 2019/2/20 15:20
 */
public class SecurityUtils {
    /**
     * @Description: 获取用户id
     * @Author: xyjxust
     * @Date: 2019/2/20 15:22
     */
    public static String getUserId() {
        User user = getPrincipal();
        if (user != null) {
            return user.getId();
        }
        return null;
    }
     /**
      * @Description: 获取用户名称
      * @Author: xyjxust
      * @Date: 2019/2/20 15:21
      */
    public static String getUsername() {
        User user = getPrincipal();
        if (user != null) {
            return user.getUsername();
        }
        return null;
    }
    /**
     * @Description: 获取用户信息
     * @Author: xiaoyuan
     * @Date: 2019/2/20 15:21
     */
    public static User getPrincipal() {
        Authentication authentication  = SecurityContextHolder.getContext().getAuthentication();
        if(authentication==null){
            ErrorType.AUTHENTICATION_ERROR.throwThis(AuthenticationException::new);
        }
        //登陆成功后已塞入需要传递的用户数据
        Object principal = authentication.getPrincipal();
        if (principal != null) {

            if (principal instanceof UserDetails) {
                return (User) principal;
            } else {
                throw new IllegalStateException("获取用户数据失败");
            }
        }
        return null;
    }

    public static String encode(String password){
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }




}
